package cn.lingyangwl.agile.pay.client.listener;

import cn.lingyangwl.framework.mq.base.manager.MqManager;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import cn.lingyangwl.agile.pay.client.model.mq.GoodsOrderRefundMQ;
import cn.lingyangwl.agile.pay.client.service.GoodsOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Lazy;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 订单超时处理
 * 死信交换机
 * 定义死信队列
 *
 * @author shenguangyang
 */
@Slf4j
@Lazy(value = false)
@Component
@RabbitListener(queues = GoodsOrderRefundMQ.QUEUE)
public class GoodsRefundListener {

    @Resource
    private MqManager mqManager;
    @Resource
    private GoodsOrderService goodsOrderService;

    @RabbitHandler
    public void onMessage(@Payload String msg, Channel channel, Message message) {
        try {
            GoodsOrderRefundMQ.MsgPayload payload = GoodsOrderRefundMQ.parse(msg, GoodsOrderRefundMQ.MsgPayload.class);
            // 判断是否重复消费
            if (mqManager.isConsumed(payload.getMsgId())) {
                log.warn("message {} are repeatedly consumed, do not perform business", payload.getMsgId());
                return;
            }
            mqManager.markConsumed(payload.getMsgId());
            if (!goodsOrderService.refund(payload)) {
                throw new BizException("退款订单失败");
            }
            log.info("{}", msg);
        } catch (Exception e) {
            log.error("exec fail: {}", e.getMessage());
            throw e;
        }
    }
}
